package com.cml.topicsystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cml.topicsystem.entity.Topic;
import com.cml.topicsystem.service.TopicService;
import com.cml.topicsystem.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cml
 * @create 2021/6/2 13:19
 */
@RestController
@RequestMapping(value = "/topic")
@CrossOrigin
public class TopicController {

    @Autowired
    private TopicService topicService;

    /**
     * 查询全部的题 按题目创建时间降序返回
     * @return
     */
    @GetMapping(value = "/selectTopic")
    public R selectTopic(){
        List<Topic> topics = topicService.list();

        List<Topic> topicList = topics.stream().sorted((a, b) -> {
            return (int) (b.getCreateTime().getTime() - a.getCreateTime().getTime());
        }).collect(Collectors.toList());

        return topicList != null ? R.ok().date(topicList) : R.error().message("获取题目数据数据失败");
    }

    /**
     * 模糊搜索题 按题目创建时间降序返回
     * @param searchInfo
     * @return
     */
    @GetMapping(value = "/selectTopicByLike/{searchInfo}")
    public R selectTopicByLike(@PathVariable("searchInfo") String searchInfo){
        QueryWrapper<Topic> topicQueryWrapper = new QueryWrapper<>();
        topicQueryWrapper.like("subject",searchInfo);
        List<Topic> topics = topicService.list(topicQueryWrapper);

        List<Topic> topicList = topics.stream().sorted((a, b) -> {
            return (int) (b.getCreateTime().getTime() - a.getCreateTime().getTime());
        }).collect(Collectors.toList());

        return topicList != null ? R.ok().date(topicList) : R.error().message("获取题目数据数据失败");
    }

    /**
     * 修改或添加题目
     * @param topic
     * @return
     */
    @PostMapping(value = "/insertOrUpdateTopic")
    public R insertOrUpdateTopic(@RequestBody Topic topic){
        Topic topic1 = topicService.getById(topic.getId());
        topic.setUpdateTime(new Date());
        if (topic1 != null){
            boolean update = topicService.updateById(topic);
            return update ? R.ok().message("添加修改成功") : R.error().message("题目修改失败");
        }

        topic.setCreateTime(new Date());
        boolean save = topicService.save(topic);
        return save ? R.ok().message("添加题目成功") : R.error().message("添加题目失败");
    }

    /**
     * 删除题目
     * @param id
     * @return
     */
    @GetMapping(value = "delete/{id}")
    public R delete(@PathVariable("id") String id){
        boolean remove = topicService.removeById(id);
        return remove ? R.ok().message("题目删除成功") : R.error().message("题目删除失败");
    }

}
